package com.example.javapracticaltraining.controller;

import com.example.javapracticaltraining.entity.pojo.UserRole;
import com.example.javapracticaltraining.entity.pojo.Users;
import com.example.javapracticaltraining.entity.vo.response.UserLoginResponseVO;
import com.example.javapracticaltraining.service.LoginService;
import com.example.javapracticaltraining.service.UserRoleService;
import com.example.javapracticaltraining.entity.R;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Tag(name = "用户登录", description = "用户登录认证接口")
@RestController
@RequestMapping("/auth")
public class LoginController {

    @Autowired
    private LoginService loginService;

    @Autowired
    private UserRoleService userRoleService;

    @Operation(summary = "用户登录", description = "根据用户名和密码进行登录认证")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "登录成功，返回用户信息"),
        @ApiResponse(responseCode = "400", description = "登录失败，用户名或密码错误")
    })
    @PostMapping("/login")
    public R<UserLoginResponseVO> login(@RequestBody Users user) {
        R<Users> loginResult = loginService.login(user.getUsername(), user.getPassword());

        if (loginResult.code() != 200) {
            return R.failure(loginResult.code(), loginResult.msg());
        }

        Users loggedInUser = loginResult.data();
        UserLoginResponseVO responseVO = new UserLoginResponseVO();
        BeanUtils.copyProperties(loggedInUser, responseVO);

        // 获取用户角色信息
        if (loggedInUser.getRoleId() != null) {
            UserRole userRole = userRoleService.getById(loggedInUser.getRoleId());
            if (userRole != null) {
                responseVO.setRoleName(userRole.getRoleName());
            }
        }

        // 生成token (实际项目中应该使用JWT或其他认证机制)
        String token = "token_" + System.currentTimeMillis();
        long expire = System.currentTimeMillis() + 24 * 60 * 60 * 1000; // 24小时后过期

        responseVO.setToken(token);
        responseVO.setExpire(expire);

        return R.success(responseVO);
    }

    @Operation(summary = "用户登出", description = "用户退出登录")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "登出成功")
    })
    @GetMapping("/logout")
    public R<String> logout() {
        // 实际项目中应该处理token失效等逻辑
        return R.success("登出成功");
    }
}
